import { GameMode } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { PKStorageConfig } from "./config";
import { PKLoadState } from "./loadState/loadState";
import { PKMaps } from "./maps";
import { parkourGameModule } from "./module";
import { ParkourContext } from "./parkourContext";
import { AutoStopState } from "@sapi-game/gameState/common/autoStop";

interface ParkourGameConfig {
    redTeam: PlayerGroup;
    blueTeam: PlayerGroup;
    pkConfig: PKStorageConfig;
    blockEnabled: boolean;
}

export class ParkourGame extends parkourGameModule.Engine<ParkourGameConfig> {
    override buildContext(config: ParkourGameConfig): ParkourContext {
        const redTeam = this.groupBuilder.fromGroup(config.redTeam);
        const blueTeam = this.groupBuilder.fromGroup(config.blueTeam);
        const PKConfig = config.pkConfig;
        return new ParkourContext(redTeam, blueTeam, {
            map: Object.values(PKMaps)[PKConfig.mapIndex],
            buildTime: PKConfig.buildTime,
            runTime: PKConfig.runTime,
            lifeCount: PKConfig.lives,
            blockEnabled: config.blockEnabled,
        });
    }

    override onStart(): void {
        this.pushState(AutoStopState, {
            groupSet: this.context.groupSet,
            onLeave: (p) => {
                this.context.blue.team.delete(p);
                this.context.red.team.delete(p);
            },
        });
        this.pushState(PKLoadState);
    }

    override onStop(): void {
        this.context.groupSet.forEach((p) => {
            p.player.runCommand("effect @s clear");
            p.player.runCommand("clear @s");
            p.player.setGameMode(GameMode.Adventure);
            p.player.teleport(
                { x: 721, y: -59, z: 435 },
                { dimension: Dimensions.Overworld }
            );
            p.player.setSpawnPoint();
        });
    }
}
